import React, {Component, Fragment} from 'react';
import {Button, Card, Table, Space, Modal, Form, Input, Select, message} from 'antd';
import {MinusOutlined, PlusOutlined, EditOutlined} from "@ant-design/icons";
import {reqBookHotWord, reqUpdateBookHotWord, reqCreateBookHotWord, reqDeleteBookHotWord} from '../../api/book';
import {dateTimeDateFormat} from "../../utils/tools";

const { Option } = Select;

// 图书关注
export default class HotBook extends Component {
  type = '';
  state = {
    result: [], // 结果
    totalCount: 0, // 数据总量
    isModalVisible: false, // 模态框显示
    modalVal: {}, // 模态框的值
    loading: false,
    category: 'word',
    selectedRowKeys: [],
  }
  // 编辑
  editClick = (record) => {
    this.type = 'edit';
    this.setState({isModalVisible: true, modalVal: record});
  }
  //添加
  addClick = () => {
    this.type = 'add';
    this.setState({isModalVisible: true});
  }
  // 初始化
  initColumns = () => {
    this.columns = [
      {
        title: '热词',
        dataIndex: 'word',
        key: 'word',
      },
      {
        title: '类型',
        dataIndex: 'category',
        key: 'category',
      },
      {
        title: '创建时间',
        dataIndex: 'add_time',
        key: 'add_time',
        render: add_time => dateTimeDateFormat(add_time)
      },
      {
        title: '编辑',
        render: (text, record) => (
          <Space>
            <Button type="primary" icon={<EditOutlined/>} title='编辑' onClick={() => this.editClick(record)}/>
          </Space>
        )
      }
    ]
  }

  UNSAFE_componentWillMount() {
    this.initColumns();
  }
  // 更新图书热词
  updateBookHotWord = async (values) => {
    try {
      const {modalVal} = this.state;
      const {data: result} = await reqUpdateBookHotWord(modalVal._id, values);
      let res = this.state.result;
      res.splice(res.indexOf(modalVal), 1, Object.assign(modalVal, result));
      this.setState({isModalVisible: false})
      message.success('更新成功!');
    } catch (e) {
      console.log(e);
      message.error(e.data.name || e.data.message);
    }
  }
  // 删除热门词
  deleteBookHotWord = async (data) => {
    try {
      await reqDeleteBookHotWord(data);
      message.success('删除成功!');
      this.getHotWords();
    } catch (e) {
      console.log(e);
    }
  }
  // 保存热门词
  saveBookHotWord = async (data) => {
    try {
      await reqCreateBookHotWord(data);
      this.setState({isModalVisible: false}, () => {
        this.getHotWords();
      });
      message.success('数据创建成功!');
    } catch (e) {
      console.log(e);
      message.error(e.data.name || e.data.message);
    }
  }
  // 热门关键词
  getHotWords = async () => {
    this.setState({loading: true});
    try {
      const {data: result} = await reqBookHotWord();
      this.setState({result: result.items, totalCount: result.total_count, loading: false});
    } catch (e) {
      message.error(e.data.name || e.data.message);
      this.setState({loading: false});
    }
  }
  // 删除关键词
  deleteClick = () => {
    const {selectedRowKeys} = this.state;
    if (selectedRowKeys.length > 0) {
      this.deleteBookHotWord({items: selectedRowKeys});
    }
  }
  // 添加
  // 点击模态框确认
  handleOk = () => {
    console.log(this.type)
    this.formRef.validateFields().then(values => {
      if (this.type === 'add') {
        this.saveBookHotWord(values);
      } else {
        this.updateBookHotWord(values);
      }
    }).catch(err => {
      console.log(err);
    })
  }
  // 关闭模态框
  handleCancel = () => {
    this.setState({isModalVisible: false})
  }
  // 多选
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  componentDidMount() {
    this.getHotWords();
  }

  render() {
    const {result, totalCount, isModalVisible, modalVal, loading, category, selectedRowKeys} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    }
    const extra = (
      <Fragment>
        <Button type='primary' onClick={this.addClick} icon={<PlusOutlined/>} style={{marginRight: '10px'}}>
          添加
        </Button>
        <Button type='primary' danger onClick={this.deleteClick} icon={<MinusOutlined/>}>
          删除
        </Button>
      </Fragment>
    )
    const pagination = {
      defaultPageSize: 5,
      position: ['bottomCenter'],
      showQuickJumper: true,
      total: totalCount,
    }

    return (
      <Card title='图书热门关键词' extra={extra}>
        <Table pagination={pagination}
               rowSelection={rowSelection}
               loading={loading}
               scroll={{x: 800}}
               columns={this.columns}
               dataSource={result}
               rowKey='_id'/>
        <Modal title="详情"
               destroyOnClose
               width={420}
               visible={isModalVisible}
               onOk={this.handleOk}
               onCancel={this.handleCancel}>
          <Form initialValues={this.type === 'edit' ? modalVal : {}}
                labelCol={{sm: {span: 4}, xs: {span: 24}}}
                wrapperCol={
                  {sm: {span: 20}, xs: {span: 24}}
                }
                ref={(instance) => this.formRef = instance}>
            <Form.Item
              name='word'
              label="热词"
              rules={[
              {
                required: true,
                message: '请输入关键词'
              }
            ]}>
              <Input/>
            </Form.Item>
            <Form.Item
              rules={[
                {
                  required: true,
                  message: '请选择类型'
                }
              ]}
              name='category'
              label='类型'>
              <Select placeholder="Please select" onSelect={(value) => {
                this.setState({category: value});
              }}>
                <Option value="book">图书</Option>
                <Option value="word">热词</Option>
              </Select>
            </Form.Item>
            <Form.Item
              rules={category === 'book' ? [
                {
                  required: true,
                  message: '请输入图书id',
                }
              ] : [{
                type: 'string',
                max: 0
              }]}
              name='book_id'
              label='图书id'>
              <Input/>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    )
  }
}
